import { PlusOutlined } from '@ant-design/icons';
import {
  ActionType,
  FooterToolbar,
  PageContainer,
  ProDescriptions,
  ProTable,
  ProForm,
  ProFormText,
  ProFormSelect,
} from '@ant-design/pro-components';
import { Button, Divider, Drawer, Modal, Space, Tag, message, Switch, Select, Avatar, Form } from 'antd';
import React, { useRef, useState, useEffect } from 'react';
import { Access, useAccess } from '@umijs/max';
import { getUserInfo, saveUser } from '@/services/system/UserController';

// 账号类型定义
type AccountItem = API.UserItem;

const AccountList: React.FC = () => {
  const [userList, setUserList] = useState<API.UserItem[]>([]);
  const [selectedUser, setSelectedUser] = useState<API.UserItem | null>(null);
  const [loading, setLoading] = useState<boolean>(false);
  const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [saveLoading, setSaveLoading] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  const access = useAccess();
  
  // 获取用户列表
  const fetchUserList = async () => {
    setLoading(true);
    try {
      const response = await getUserInfo();
      if (response.code === '200') {
        setUserList(response.data);
        message.success('获取用户列表成功');
      } else {
        message.error(response.message || '获取用户列表失败');
      }
    } catch (error) {
      console.error('获取用户列表出错:', error);
      message.error('获取用户列表出错');
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载时获取用户列表
  useEffect(() => {
    fetchUserList();
  }, []);

  // 查看用户详情
  const handleViewDetail = (record: AccountItem) => {
    setSelectedUser(record);
    setDrawerVisible(true);
  };
  
  // 处理添加用户
  const handleAddUser = () => {
    form.resetFields();
    setModalVisible(true);
  };

  // 处理保存用户
  const handleSaveUser = async (values: any) => {
    setSaveLoading(true);
    try {
      const userData: API.UserItem = {
        userName: values.userName,
        phone: values.phone,
        wxId: values.platform,
        headerPhoto: 'https://example.com/avatar.jpg', // 默认头像
        token: values.password || null,
        id: 0, // 新用户ID为0，后端会自动分配
      };
      
      const response = await saveUser(userData);
      if (response.code === '200') {
        message.success('添加用户成功');
        setModalVisible(false);
        fetchUserList(); // 刷新用户列表
      } else {
        message.error(response.message || '添加用户失败');
      }
    } catch (error) {
      console.error('添加用户出错:', error);
      message.error('添加用户出错');
    } finally {
      setSaveLoading(false);
    }
  };
  
  // 表格列定义
  const columns = [
    {
      title: '用户头像',
      dataIndex: 'headerPhoto',
      valueType: 'avatar',
      hideInSearch: true,
      render: (_, record) => (
        <Avatar src={record.headerPhoto} size="large" />
      ),
    },
    {
      title: 'ID',
      dataIndex: 'id',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '用户名',
      dataIndex: 'userName',
      valueType: 'text',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      valueType: 'text',
    },
    {
      title: '微信ID',
      dataIndex: 'wxId',
      valueType: 'text',
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_, record) => [
        <a key="view" onClick={() => handleViewDetail(record)}>
          查看
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<AccountItem>
        headerTitle="账号管理"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="add"
            icon={<PlusOutlined />}
            onClick={handleAddUser}
          >
            添加账号
          </Button>,
          <Button
            type="primary"
            key="refresh"
            onClick={() => fetchUserList()}
            loading={loading}
          >
            刷新
          </Button>,
        ]}
        dataSource={userList}
        columns={columns}
        pagination={{
          showQuickJumper: true,
          pageSize: 10,
        }}
      />

      <Drawer
        width={600}
        open={drawerVisible}
        onClose={() => {
          setDrawerVisible(false);
          setSelectedUser(null);
        }}
        closable={false}
      >
        {selectedUser && (
          <ProDescriptions<AccountItem>
            column={2}
            title="用户详情"
            dataSource={selectedUser}
            columns={columns}
          />
        )}
      </Drawer>

      <Modal
        title="添加账号"
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSaveUser}
        >
          <Form.Item
            name="userName"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <ProFormText placeholder="请输入用户名" />
          </Form.Item>
          
          <Form.Item
            name="phone"
            label="手机号"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1\d{10}$/, message: '请输入有效的手机号' }
            ]}
          >
            <ProFormText placeholder="请输入手机号" />
          </Form.Item>
          
          <Form.Item
            name="platform"
            label="平台"
            rules={[{ required: true, message: '请输入平台' }]}
          >
            <ProFormText placeholder="请输入平台" />
          </Form.Item>
          
          <Form.Item
            name="password"
            label="密码"
          >
            <ProFormText.Password placeholder="请输入密码（可选）" />
          </Form.Item>
          
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" loading={saveLoading}>
                保存
              </Button>
              <Button onClick={() => setModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default AccountList;
